package cn.boat.router.producer;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;
//创建连接对象

public class connect {
    public static void main(String[] args) throws Exception{
        try {
            // 计数器对象
            final CountDownLatch countDownLatch=new CountDownLatch(1);
            // arg1:服务器的ip和端口
            // arg2:客户端与服务器之间的会话超时时间  以毫秒为单位的
            // arg3:监视器对象

            final ZooKeeper zooKeeper=new ZooKeeper("192.168.56.101:2181",
                    5000, new Watcher() {
                @Override

                public void process(WatchedEvent event) {
                    if(event.getState()==Event.KeeperState.SyncConnected) {
                        System.out.println("连接创建成功!");
                        countDownLatch.countDown();
                    }else if (event.getState()== Event.KeeperState.Disconnected){
                        System.out.println("zookeeper连接失败");
                    }
                }
            });
            // 主线程阻塞等待连接对象的创建成功
            countDownLatch.await();
            // 会话编号
            System.out.println(zooKeeper.getSessionId());
            //一串整型值，表示当前客户端与zookeeper服务器之间建立会话的id
            zooKeeper.close();
            //资源释放
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

